package com.cacho.s2b.lesson.learn;

import com.opencsv.CSVReader;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description Opencsv 处理CSV文件
 * @Author LingWei
 * @date 2023/12/31
 **/
@Slf4j
public class LearnOpencsv {
    public LearnOpencsv(){}
    public static void main( String[] args ) {
        String csvPath = "F:\\JavaProject\\api_def.csv";
        readAllCsv(csvPath);
    }
    // readNext() 一行一行度读
    public static void readLineCsv(String csvPath){
        try {
            FileReader fileReader = new FileReader(csvPath);
            CSVReader reader = new CSVReader(fileReader);
            String[] nextLine;
            // 直到最后一行为空结束
            while ((nextLine=reader.readNext())!=null){
                for (String cell:nextLine){
                    System.out.print(cell+",");
                }
                System.out.println();
            }
            reader.close();
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    public static void readAllCsv(String csvPath){
        try {
            FileReader fileReader = new FileReader(csvPath);
            CSVReader reader = new CSVReader(fileReader);
            List<String[]> entries = reader.readAll();
            if (entries.isEmpty()) {
                System.out.printf("Csv文件 %s为空",csvPath); //printf
            } else{
                int rowSize = entries.size();
                System.out.println("Csv文件行数："+rowSize);
                System.out.println("第一行title："+Arrays.toString(entries.get(0)));
                int columnSize = entries.get(0).length;
                System.out.println("第一行title列长度："+columnSize);
                for (String[] s : entries) {
                    if (s.length==columnSize){
                        System.out.println(Arrays.toString(s));
                    }
                    else{
                        System.out.printf("Csv文件 %s,列%s长度%s不符合要求：",csvPath,Arrays.toString(s),s.length);
                    }
                }
            }
            reader.close();
        } catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
